<script setup lang="ts">
import SonCom from "./components/SonCom.vue";
import HmButton from "./components/HmButton.vue";
import { provide, ref } from "vue";
import HmNavbar from "./components/HmNavbar.vue";

// 父组件传递回调函数给子组件，子组件触发回调函数
const myEvent = (age: number) => {
  console.log("子组件触发回调函数", age);
};

const getName = (name: string) => {
  console.log("子组件触发回调函数", name);
};
// 父(祖先)组件通过provide传递数据给子组件
const totalCount = ref(0);
// 1. provide 函数类似鸿蒙的 @Provide 装饰器，祖先提供数据
provide("totalCount", totalCount);
// 父(祖先)组件给子组件传回调函数
provide("updateTotalCount", (num: number) => {
  totalCount.value += num;
});

// 接收子组件传递的数据
const appTitle = ref("应用标题");
const leftClick = (val: string) => {
  alert(val);
};
</script>

<template>
  <HmNavbar v-bind:title="appTitle" @left-click-handler="leftClick">
    <!-- 给插槽传值 不传过去就会显示 HmNavbar 中默认内容-->
    <button>按钮</button>
  </HmNavbar>
  <h1>App 根组件</h1>
  <!-- 
    父传子：通过 v-bind: 和 props 传递数据
    子传父：通过 v-on: 和 emits 传递数据（传回调函数给子组件调用）
  -->
  <h1>根组件:totalCount:{{ totalCount }}</h1>
  <!-- 父传子 -->
  <button @click="totalCount++">修改数据+1</button>
  <SonCom
    :name="'张三'"
    :age="18"
    @my-event="myEvent($event)"
    @get-name="getName($event)"
  ></SonCom>
  <SonCom
    :name="'李四'"
    :age="20"
    @my-event="myEvent"
    @get-name="getName"
  ></SonCom>
  <!--父传子，text为可选参数-->
  <HmButton :text="'登录'" />
  <HmButton :text="'注册'" />
  <HmButton />
</template>

<style scoped></style>
